//mapscript.js
var infos = [];
var loading = false;
var displayCount = 0;
 
function Info (infoArray) {
	var infoVars = [ 'latitude', 'longitude', 'location', 'caption'];
	for (var i = 0; i < infoVars.length; i++) {
		this[infoVars[i]] = infoArray[i];
	}
}
 
Info.prototype.lastStatus = function () {
	var myDiv = document.createElement('div');
	myDiv.innerHTML = this.text;
	myDiv.id = "lastStatus";
	return myDiv;	
}
 
Info.prototype.infoWindow = function() {
	var myInfoWindow = document.createElement('div');
	myInfoWindow.id = "infoWindow";
	myInfoWindow.appendChild(this.lastStatus());
	return myInfoWindow;
}
 
function loadData() {
	if (!loading) {
		new Ajax.Request('updates.php', { 
			method : 'post',
			onCreate : function () { loading = true; },
			onSuccess : function(transport) {addInfos(transport.responseText);},
			onComplete : function () { loading = false; } 
		});
	}
}
 
function showInfos() {
	var currentInfo = infos.pop();
	if ( currentInfo && currentInfo.show ) {
		currentInfo.show();
		displayCount++;
	}
	if (infos.length == 0)
		loadData();
	setTimeout("showInfos();", 5000);
}
 
function addInfos(responseText) {
	var newInfos = eval(responseText);
	if (newInfos.length == 0)
		alert("No Infos Available!");
	else {	
		for (i=0; i<newInfos.length; i++) {
			infos.push(new Info(newInfos[i]));
		}
	}
	if (displayCount == 0)
		showInfos();
}
 
var map;
var userMarker;
var marker;
var map_icon = addOptionsToIcon(new GIcon(),{iconSize : new GSize(48,48), iconAnchor : new GPoint(18,43), infoWindowAnchor : new GPoint(45,20), image : '/images/icon.png', shadow : 'images/birdshadow.png'});

// add options to a GMaps icon
function addOptionsToIcon(icon, options) {
	for(var k in options)	{
		icon[k] = options[k];
	}
	return icon;
}
 
function loadMap () {
	var w = 400; // Width of map container
	map = new GMap2(document.getElementById("map"), {mapTypes: [G_NORMAL_MAP] });
	map.setCenter(new GLatLng(13.703276,100.324402), 11);
	map.addControl(new GSmallMapControl());	
}
 
Info.prototype.show = function () {
	// clear marker
	map.closeInfoWindow();
	if (marker)
		map.removeOverlay(marker);
	// show marker with infoWindow
	marker = new GMarker(new GLatLng(this.latitude,this.longitude), { icon : map_icon });
	map.addOverlay(marker);
	map.openInfoWindow(marker.getLatLng(), this.infoWindow(), {noCloseOnClick : true} );
}
 
addEvent(window, 'load', init);
function init() {
	if (GBrowserIsCompatible()) {    
		loadMap();
		loadData();
	} else {
		alert("Sorry, your browser isn't compatible with Google Maps!")
	}
}
 
function addEvent(obj, evType, fn){ 
	if (obj.addEventListener){ 
   		obj.addEventListener(evType, fn, false); 
   		return true; 
 	} else if (obj.attachEvent){ 
   		var r = obj.attachEvent("on"+evType, fn); 
   		return r; 
 	} else { 
   		return false; 
 	} 
}